package com.juyu.miliao.api.controller;

import com.juyu.miliao.api.domain.QuestionAndAnswerInfo;
import com.juyu.miliao.api.domain.vo.QuestionAndAnswerVo;
import com.juyu.miliao.api.service.QuestionAndAnswerInfoService;
import com.juyu.miliao.api.validator.CreateQuestionAndAnswerInfoCheck;
import com.juyu.miliao.api.validator.UpdateQuestionAndAnswerInfoCheck;
import com.juyu.miliao.common.domain.Subject;
import com.juyu.miliao.common.exception.ConsumeRuntimeException;
import com.juyu.miliao.common.exception.IllegalParamException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;


/**
 * 提问控制器
 *
 * @author xuanqicheng
 * @create 2018-14-3:54 PM
 */
@RestController
public class QuestionAndAnswerInfoController {

    @Autowired
    private QuestionAndAnswerInfoService andAnswerInfoService;

    @PostMapping("/question/create")
    public void createQuestionInfo(Authentication token,
                                   @Validated(CreateQuestionAndAnswerInfoCheck.class)
                                           QuestionAndAnswerInfo questionAndAnswerInfo,
                                   BindingResult bindingResult){

        if(bindingResult.hasErrors()){
            throw  new ConsumeRuntimeException(bindingResult.getFieldError().getDefaultMessage());
        }


        //获取提问者id
        Subject subject = (Subject) token.getPrincipal();

        if (subject.getId() != questionAndAnswerInfo.getQuestionUserId()){
            throw new ConsumeRuntimeException("提问者Id不正确");
        }else{

            andAnswerInfoService.createInfo(questionAndAnswerInfo);

        }

    }

    @PostMapping("/answer/update")
    public void updateQuestionInfo(Authentication token,
                                   @Validated(UpdateQuestionAndAnswerInfoCheck.class)
                                           QuestionAndAnswerInfo questionAndAnswerInfo,
                                   BindingResult bindingResult){
        if(bindingResult.hasErrors()){
            throw  new ConsumeRuntimeException(bindingResult.getFieldError().getDefaultMessage());
        }

        //获取提回答人id
        Subject subject = (Subject) token.getPrincipal();

        QuestionAndAnswerInfo obj = andAnswerInfoService.getEntity(questionAndAnswerInfo.getId());

        if(obj==null){
            throw new ConsumeRuntimeException("问题Id不正确");
        }

        if (subject.getId() != obj.getAnswerUserId()){
            throw new ConsumeRuntimeException("回答人Id不正确");
        }else{
            andAnswerInfoService.updateInfo(questionAndAnswerInfo);
        }
    }


}
